<?php

namespace app\common\model;

use app\common\model\Coupons as CouponsModel;
use app\common\model\UserCoupons as UserCouponsModel;
use think\Model;


class UserCoupons extends Model
{

    

    

    // 表名
    protected $name = 'user_coupons';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
    ];



    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function coupons()
    {
        return $this->belongsTo('app\common\model\Coupons', 'coupons_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function sendCoupons($user_id, $coupon_id, $number)
    {
        $CouponsModel = new CouponsModel();
        $UserCouponModel = new UserCouponsModel();
        $UserCouponsLog = new UserCouponsLog();
        $couponsInfo = $CouponsModel->where(['id' => $coupon_id])->find();
        $_time = time();

        $alreadyCoupons = $UserCouponModel->where([
            'user_id' => $user_id,
            'coupons_id' => $coupon_id,
        ])->find();
        if($alreadyCoupons){
            $UserCouponModel->where([
                'id' => $alreadyCoupons['id'],
            ])->update([
                'nums' => $number + $alreadyCoupons['nums'],
                'buyed' => $number + $alreadyCoupons['buyed'],
                'updatetime' => $_time
            ]);
            $user_coupons_id = $alreadyCoupons['id'];
        }else{
            $user_coupons_id = $UserCouponModel->insertGetId([
                'buyed' => $number,
                'nums' => $number,
                'price' => $couponsInfo['price'],
                'coupons_id' => $coupon_id,
                'user_id' => $user_id,
                'createtime' => $_time,
            ]);
        }

        $coupons_log = [
            'nums' => $number,
            'price' => $couponsInfo['price'],
            'coupons_id' => $coupon_id,
            'user_coupons_id' => $user_coupons_id,
            'user_id' => $user_id,
            'type' => 'send'
        ];
        return $UserCouponsLog->save($coupons_log);
    }

}
